//
//  XWFunc.swift
//  XWNetworking
//
//  Created by Miles on 2023/10/12.
//

import Foundation
#if os (macOS)
import Cocoa
import CoreMedia
#elseif os(iOS)
import UIKit
#endif


func XWLog<T>(_ content: T, file: String = #file, functionName: String = #function, line: Int = #line) {
    let fileString = (file as NSString).lastPathComponent
#if DEBUG
    print("\(fileString) line:\(line) func:\(functionName)->>>>>  content:\(content)")
#endif
}


#if os(macOS)
func getMacDeviceModel() -> String {
    if let model = SysctlByName("hw.model") {
        return model
    }
    return "Unknown"
}

func SysctlByName(_ name: String) -> String? {
    var size: size_t = 0
    sysctlbyname(name, nil, &size, nil, 0)
    guard size > 0 else { return nil }

    var value = [CChar](repeating: 0, count: size)
    sysctlbyname(name, &value, &size, nil, 0)

    return String(cString: value)
}

#endif

func getOSVersion() -> String {
#if os(iOS)
    let systemVersion = UIDevice.current.systemVersion
    return "iOS " + systemVersion
#elseif os(macOS)
    let os = ProcessInfo().operatingSystemVersion
    let versionString = "\(os.majorVersion).\(os.minorVersion).\(os.patchVersion)"
    return "macOS " + versionString
#endif
}

/// 获取系统版本号 例如 "macOS Version 13.4 (Build 22F66)"
public func getDeviceModel() -> String {
#if os(iOS)
    return "iOS " +  UIDevice.current.systemVersion
#elseif os(macOS)
    return "macOS " +  ProcessInfo.processInfo.operatingSystemVersionString
#endif
    

}

/// 获取设备型号 例如 "Mac14,3"
public func getDeviceName () -> String {
#if os(iOS)
    var systemInfo = utsname()
    uname(&systemInfo)
    let machineMirror = Mirror(reflecting: systemInfo.machine)
    let identifier = machineMirror.children.reduce("") { (identifier, element) in
        guard let value = element.value as? Int8, value != 0 else { return identifier }
        return identifier + String(UnicodeScalar(UInt8(value)))
    }
    return identifier
#elseif os(macOS)
    var size: size_t = 0
       sysctlbyname("hw.model", nil, &size, nil, 0)
       var model = [CChar](repeating: 0,  count: size)
       sysctlbyname("hw.model", &model, &size, nil, 0)
       return String(cString: model)
#endif
}

public func getPlatform () -> String {
#if os(iOS)
    return "3"
#elseif os(macOS)
    return "1"
#endif
}


public enum MyError: Error {
    case invalidURL
}

//MARK:  校验URL
public func validateURL(_ urlString: String) throws -> URL {
    if let url = URL(string: urlString) {
        return url
    } else {
        throw MyError.invalidURL
    }
}

// MARK: 字典转json字符串
public func xwDicValueString(_ dic:[String : Any]) -> String?{
    
    let  data :Data! = try? JSONSerialization.data(withJSONObject: dic, options: [])
    var  jsonStr = String(data: data, encoding: String.Encoding(rawValue: String.Encoding.utf8.rawValue))
    jsonStr = jsonStr?.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)
    jsonStr = jsonStr?.replacingOccurrences(of: "\r", with: "")
    jsonStr = jsonStr?.replacingOccurrences(of: "\n", with: "")
    
    return jsonStr
}

// MARK: json字符串转字典
public func xwStringValueDic(_ str: String) -> [String : Any]{
    if let data = str.data(using: String.Encoding.utf8) {
        do {
            return try JSONSerialization.jsonObject(with: data, options: [JSONSerialization.ReadingOptions.init(rawValue: 0)]) as? [String : Any] ?? [:]
        } catch let error as NSError {
            XWLog(error)
        }
    }
    return [:]
}

#if os (macOS)

public func xwBufferDifference(buffer: CMSampleBuffer, other: CMSampleBuffer) -> Float {
    guard let buffer1 = CMSampleBufferGetImageBuffer(buffer),
          let buffer2 = CMSampleBufferGetImageBuffer(other) else {
        return 0.0
    }
    // 将两个图像转换成 CIImage 对象
    let ciImage1 = CIImage.init(cvPixelBuffer: buffer1)
    let ciImage2 = CIImage.init(cvPixelBuffer: buffer2)
    
    let diff = xwImageDifference(image: ciImage1, other: ciImage2)
    return diff
}

#endif

public func xwImageDifference(image: CIImage, other: CIImage) -> Float {
    let ciImage1 = image
    let ciImage2 = other
    
    // 创建并配置滤镜，黑白色
    let filter = CIFilter(name: "CIFalseColor")!
    filter.setValue(ciImage1, forKey: kCIInputImageKey)

    // 将第一张图片渲染为位图数据
    let context = CIContext(options: nil)
    guard let outputImage1 = filter.outputImage,
          let bitmap1 = context.createCGImage(outputImage1, from: outputImage1.extent) else {
        return 0.0
    }

    // 重置滤镜配置
    filter.setValue(ciImage2, forKey: kCIInputImageKey)

    // 将第二张图片渲染为位图数据
    guard let outputImage2 = filter.outputImage,
          let bitmap2 = context.createCGImage(outputImage2, from: outputImage2.extent) else {
        return 0.0
    }

    // 计算两张图片的相似度
    let dataProvider1 = bitmap1.dataProvider
    let dataProvider2 = bitmap2.dataProvider
    let data1 = dataProvider1?.data
    let data2 = dataProvider2?.data

    let bytes1 = CFDataGetBytePtr(data1)
    let bytes2 = CFDataGetBytePtr(data2)

    let length1 = CFDataGetLength(data1)
    let length2 = CFDataGetLength(data2)

    var difference: Float = 0.0

    if length1 == length2 {
        for i in 0..<length1 {
            difference += Float(abs(Int(bytes1![i]) - Int(bytes2![i])))
        }

        difference /= Float(length1)
    }
    return difference
}
